/*
 * Copyright (C) 2010,  Tomislav Milkovic
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 * 
 */
package hr.ws4is.websocket;

import hr.ws4is.JsonDecoder;
import hr.ws4is.websocket.data.WebSocketResponse;
import java.io.IOException;
import javax.enterprise.inject.Vetoed;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
import com.fasterxml.jackson.databind.ObjectMapper;

@Vetoed
public class WebsocketEncoder implements Encoder.Text<WebSocketResponse> {
	private ObjectMapper mapper = null;
		
	@Override
	public void destroy() {
		mapper = null;
	}

	@Override
	public void init(EndpointConfig arg0) {	
		mapper = JsonDecoder.getJSONEngine();
	}

	@Override
	public String encode(WebSocketResponse data) throws EncodeException	{
		String response = null;
		try {
			if(mapper!=null){
				response = mapper.writeValueAsString(data);				
			}			
		} catch (IOException e) {
			e.printStackTrace();
			throw new EncodeException(data, e.getMessage(), e);
		}
		if(response == null){
			response = "";
		}
		return response;
	}	

}
